package com.sky.service.impl;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        /**
         * 前端给了我们数据，剩下的我们要自己维护传递上去
         * id有自增,我们设置状态-创建时间-结束时间-和创建人即可
         */
        Employee employe = new Employee();
        //设置添加后的状态
        employe.setStatus(StatusConstant.ENABLE);
        //把传递过来的数据都添加到创建的对象中
        BeanUtils.copyProperties(employeeDTO,employe);
        //创建添加用户时间和结束时间
        employe.setCreateTime(LocalDateTime.now());
        employe.setUpdateTime(LocalDateTime.now());
        //添加默认密码
        employe.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //获取当前创建人
        //先查出当前登录的id
        employe.setCreateUser(BaseContext.getCurrentId());
        employe.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.addEmployee(employe);

    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageSelectEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        //用第三方分页查询工具来进行分页
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        //根据条件进行查询数据库
        List<Employee> employee = employeeMapper.pageSelectEmployee(employeePageQueryDTO.getName());

        //进行判断
        if (employee.size() == 0) {
            throw new BaseException();
        }
        //封装成Page对象 本来有数据？
        Page pageInfo = (Page) employee;

        //传递给PageResult
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getResult());

        //返回给调用者
        return pageResult;
    }

    /**
     * 状态修改功能
     * @param status
     * @param id
     */
    @Override
    public void updateEnableDisable(Integer status, Integer id) {
        Employee build = Employee.builder()
                .id(Long.valueOf(id))
                .status(status)
                .build();
        employeeMapper.updateEnableDisable(build);
    }

    /**
     *数据回显，根据id查询数据
     * @param id
     * @return
     */
    @Override
    public Employee selectByIdEmployee(Integer id) {
        Employee employee = employeeMapper.selectByIdEmployee(id);
        return employee;
    }

    /**
     * 修改员工方法
     * @param employeeDTO
     */

    @Override
    public void updateEmployee(@Param("employeeDTO") EmployeeDTO employeeDTO) {
        //动态获取设置修改人
        Long currentId = BaseContext.getCurrentId();
        employeeMapper.updateEmployee( employeeDTO);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void updateEmployeePassword(PasswordEditDTO passwordEditDTO) {
        //原始密码
        String oldPassword = passwordEditDTO.getOldPassword();
        //获取用户当前密码
        Employee employee = employeeMapper.selectByIdEmployee(Math.toIntExact((BaseContext.getCurrentId())));
        //得到当前账户密码
        String password = employee.getPassword();
        //得到当前账户id赋值给PasswordEditDTO中
        passwordEditDTO.setEmpId(employee.getId());
        //进行判断,把原始密码进行MD5加密和数据库里的密码进行判断
        String oldPassword1 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if(oldPassword1.equals(password)){
            //把新密码进行MD5加密存入数据库
            passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
            employeeMapper.updateEmployeePassword(passwordEditDTO);
        }else {
            throw new PasswordErrorException();
        }
    }
}
